<?php

namespace App\Http\Controllers\Resources;

use App\EmptyObject;
use App\Jobs\SendResetMessage;
use App\Jobs\SendResetPassEmail;
use App\Models\Company;
use App\Mail\PassWord;
use App\Models\User;
use App\Models\WxClient;
use App\Services\Interfaces\RepoServiceInterface;
use App\Services\PlatformService;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use \App\Http\Requests\CompanyRequest;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
use Helper;
use Illuminate\Support\Facades\Redis;
use Laravel\Passport\ClientRepository;
use Laravel\Passport\PersonalAccessClient;

class CompanyController extends Controller
{
    public function __construct(RepoServiceInterface $_repoService)
    {
        $this->_repoService = $_repoService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
            $data = $this->_repoService->read();
            return $data;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $user = Auth::user();
        $company = new Company();

        if($user->can('create', $company)){
            return view("company.add");
        }

        if($user->cannot('create', $company)){
            return $this->_error('null authority!');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  CompanyRequest  $request
     * @return Company
     */
    public function store(CompanyRequest $request)
    {
        // 获取Company参数
        $inputs = $this->getInputs($request);
        $wxClientsCount = array_get($inputs, 'wxClientsCount', 0);
        $wxClientIds = $request->input('wxClients', []);
        if ((new PlatformService)->isUserExist(array_get($inputs, 'contactTel', ''),
            array_get($inputs, 'email', ''))) {
            return $this->_error('该渠道联系人的手机或邮箱已存在帐号');
        }
        if (count($wxClientIds) < intval($wxClientsCount)) {
            return $this->_error('实际分配的空闲微信号数量小于需要的数量。');
        }
        $newCom = $this->_repoService->create($inputs);
        if (is_null($newCom)) {
            $errMsg = config('app.debug') ? '创建时发生异常,请查看日志确定错误。' : '创建渠道失败, 请检查参数。';
            return $this->_error($errMsg);
        }

        // 增加使用令牌
        $options = $newCom->options;
        if (array_key_exists('needToken', $options) && $options['needToken']) {
            $clientRepository = new ClientRepository();
            $name = $newCom->alias;
            $client = $clientRepository->createPersonalAccessClient(
                null,
                $name,
                'http://localhost'
            );

            $accessClient = new PersonalAccessClient();
            $accessClient->client_id = $client->id;
            $accessClient->save();

            $options['client_id'] = $client->id;
            $newCom->options = $options;
            $newCom->save();
        }
        /** @var Company $newCom **/
        return $newCom;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $result = $this->_repoService->find(['_id' => $id]);
        $data = $result ?? new EmptyObject();
        return $data;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $companyInfo = Company::find($id);
        if(!is_null($companyInfo)){

            $user = Auth::user();

            if($user->can('update', $companyInfo)){
                return view('company.edit', compact('companyInfo'));
            }

            if($user->cannot('update', $companyInfo)){
                return $this->_error('null authority!');
            }
        }else{
            return $this->_error('not find this model');
        }
    }

    /**
     * Update the specified resource in storage.
     * 这里为PUT请求
     * @param CompanyRequest $request
     * @param  int $id
     * @return mixed
     */
    public function update(CompanyRequest $request, $id)
    {
        $inputs = $this->getInputs($request);
        $wxClients = $request->input('wxClients', []);
        $request->session()->flash('wxClients', $wxClients);
        $this->_repoService->update(['_id' => $id], $inputs);
        return $this->_repoService->find(['_id' => $id]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $company = Company::find($id);
        if (is_null($company)) {
            return $this->_error('该渠道不存在');
        }
        if($company->delete()){
            return $this->show($id);
        }
        return $this->_error('failed');
    }

    public function option($id){
        if(
            Company::onlyTrashed()
            ->where('_id', $id)
            ->restore()
        ){
            return $this->show($id);
        }

        return $this->_error('failed');
    }

    protected function getInputs(Request $request) {
        $inputs = [];
        $date = ['startDate', 'endDate'];
        foreach (Company::InputFiled as $key => $default) {
            if (in_array($key, $date)) {
                $inputs[$key] = (!empty($request->input($key))) ? $request->input($key) : $default;
            } else {
                $inputs[$key] = $request->input($key, $default);
            }
        }
        return $inputs;
    }

    /**
     * 重置密码
     * @FunName: resetPassword
     * @Param: * @param $id
     */
    public function resetPassword($id) {
        $company = Company::find($id);
        if (!is_null($company)) {
            // initUser是字符串，但是为什么打印出来的是对象？
            // initUser对象里面有user_id和password两个属性
            $initUser = $company->initUser;
            $user_id = $initUser->user_id;
            $password = $initUser->password;
            $user = User::find($user_id);

            if (!is_null($user)) {
                $user->password = bcrypt($password);
                $isSave = $user->save();

                $userInfo = [];
                $userInfo['email'] = $user->email;
                $userInfo['mobile'] = $user->mobile;
                $userInfo['name'] = $user->name;
                $userInfo['alias'] = array_get($company, 'alias', 'p');
                $userInfo['password'] = $password;
                if ($isSave) {
                    $job = new SendResetPassEmail($userInfo);
                    $jobSendMessage = new SendResetMessage($userInfo);
                    dispatch($job);
                    dispatch($jobSendMessage);
                    return "重置密码成功！";
                } else {
                    return $this->_error("重置密码失败！");
                }
            } else {
                return $this->_error("此渠道管理员账号不存在");
            }
        } else {
            return $this->_error("此渠道不存在");
        }
    }

}
